﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace REVISIONMAX30
{
    public partial class frmGroup : DockContent
    {
        public frmGroup()
        {
            InitializeComponent();
        }

        public UIHandler uiHandler { get; set; }
        public DataObjects.Group group { get; set; }
        public DataObjects.DataMain dataMain { get; set; }

        public void View(UIHandler pUIHandler, DataObjects.Group pChildObject, DataObjects.DataMain pParentObject)
        {
            this.uiHandler = pUIHandler;
            this.group = pChildObject;
            this.dataMain = pParentObject;
            this.UpdateViewer();
        }

        public void UpdateViewer()
        {
            this.txtGroupName.Text = this.group.GroupName;
            this.txtCurrentRevision.Text = this.group.CurrentRevision.StringValueOrEmpty();
            this.mySQLItemList.Initzialize(this.uiHandler, this.group);
            this.mySourceList.Initzialize(this.uiHandler, this.group);
            this.myLogList.Initzialize(this.uiHandler, this.group);
            this.myConnectionStringList.Initzialize(this.uiHandler, this.group);
        }

        private void UpdateObject()
        {
            this.group.GroupName = this.txtGroupName.Text;
            this.group.CurrentRevision = this.txtCurrentRevision.Text.IntValueOrZero();
        }

        public Guid DataObjectGUID
        {
            get { return this.group.DataObjectGUID; }
        }
 
        private void btnApply_Click(object sender, EventArgs e)
        {
            this.Save(true);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("are you sure you want to delete this group?", "are you sure you want to delete this group?", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                //List<int> idArray = new List<int>();
                //idArray.Add(this.group.id);
                //Common.DeleteGroups(idArray);
                //this._uiHandler.groupPanel.UpdateViewer();
                //base.Close();
            }
        }

        private void btnDumpDBsToBackup_Click(object sender, EventArgs e)
        {
            var tFrResult = this.group.DumpDBsToBackUp();

        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            //StringBuilder builder = new StringBuilder();
            //List<SQLItem> sQLItemListForExecution = Common.GetSQLItemListForExecution(this.group);
            //SortedList<int, string> connectionStringIdValueList = Common.GetConnectionStringIdValueList(this.group);
            //try
            //{
            //    foreach (SQLItem item in sQLItemListForExecution)
            //    {
            //        if (connectionStringIdValueList.ContainsKey(item.connectionstringid))
            //        {
            //            string connectionString = connectionStringIdValueList[item.connectionstringid];
            //            MySqlConnectionStringBuilder builder2 = new MySqlConnectionStringBuilder(connectionString);
            //            using (SQLiteConnection connection = Common.GetSQLiteConnection())
            //            {
            //                string str2;
            //                StringBuilder builder3;
            //                connection.Open();
            //                Log pErrorLog = new Log("", this.group, connection);
            //                Log pOutLog = new Log("", this.group, connection);
            //                if (item.sourcetype == "sqlfile")
            //                {
            //                    str2 = Common.ExecuteBatch(builder2.UserID, builder2.Password, builder2.Database, item.source, pErrorLog, pOutLog);
            //                    if (!str2.IsEmpty())
            //                    {
            //                        builder.AppendLine(str2);
            //                    }
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                    item.executed = new DateTime?(DateTime.Now);
            //                    builder.Append(item.SaveOrUpdate().ToString());
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                    this.group.lastrevision = item.revision;
            //                }
            //                else if (item.sourcetype == "sourcetext")
            //                {
            //                    string tempFileName = Path.GetTempFileName();
            //                    File.WriteAllText(tempFileName, item.source);
            //                    str2 = Common.ExecuteBatch(builder2.UserID, builder2.Password, builder2.Database, tempFileName, pErrorLog, pOutLog);
            //                    File.Delete(tempFileName);
            //                    if (!str2.IsEmpty())
            //                    {
            //                        builder.AppendLine(str2);
            //                    }
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                    item.executed = new DateTime?(DateTime.Now);
            //                    builder.Append(item.SaveOrUpdate().ToString());
            //                    if (builder.Length > 0)
            //                    {
            //                        break;
            //                    }
            //                    this.group.lastrevision = item.revision;
            //                }
            //                if (!pErrorLog.value.IsEmpty())
            //                {
            //                    builder3 = new StringBuilder();
            //                    builder3.AppendLine(string.Format("error executing: {0}", item.source));
            //                    builder3.AppendLine("------------------------------------------------------------------");
            //                    builder3.AppendLine(pErrorLog.value);
            //                    builder3.AppendLine("------------------------------------------------------------------");
            //                    pErrorLog.value = builder3.ToString();
            //                    pErrorLog.SaveOrUpdate();
            //                }
            //                if (!pOutLog.value.IsEmpty())
            //                {
            //                    builder3 = new StringBuilder();
            //                    builder3.AppendLine(string.Format("output executing: {0}", item.source));
            //                    builder3.AppendLine("------------------------------------------------------------------");
            //                    builder3.AppendLine(pOutLog.value);
            //                    builder3.AppendLine("------------------------------------------------------------------");
            //                    pOutLog.value = builder3.ToString();
            //                    pOutLog.SaveOrUpdate();
            //                }
            //            }
            //        }
            //    }
            //    this.group.SaveOrUpdate();
            //}
            //catch (Exception exception)
            //{
            //    builder.AppendLine(string.Format("Error: {0}", exception.Message));
            //}
            //if (builder.Length > 0)
            //{
            //    MessageBox.Show(builder.ToString());
            //}
            //this.UpdateViewer();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            //StringBuilder builder = new StringBuilder();
            //try
            //{
            //    using (SQLiteConnection connection = Common.GetSQLiteConnection())
            //    {
            //        connection.Open();
            //        using (SQLiteCommand command = connection.CreateCommand())
            //        {
            //            command.CommandText = string.Format("update sqlitems set `executed` = null where parentid = {0} ", this.group.id);
            //            command.ExecuteNonQuery();
            //        }
            //    }
            //    this.group.lastrevision = 0;
            //    this.group.SaveOrUpdate();
            //}
            //catch (Exception exception)
            //{
            //    builder.AppendLine(string.Format("Error: {0}", exception.Message));
            //}
            //if (builder.Length > 0)
            //{
            //    MessageBox.Show(builder.ToString());
            //}
            //this.UpdateViewer();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            //this.Save(false);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            //StringBuilder errors = new StringBuilder();
            //try
            //{
            //    using (SQLiteConnection connection = Common.GetSQLiteConnection())
            //    {
            //        connection.Open();
            //        using (SQLiteTransaction transaction = connection.BeginTransaction())
            //        {
            //            using (SQLiteCommand command = connection.CreateSQLItemCommand())
            //            {
            //                List<Source> sourceList = Common.GetSourceList(this.group);
            //                SortedList<string, int> connectionStringNameIdList = Common.GetConnectionStringNameIdList(this.group);
            //                SortedList<string, SQLItem> sQLItemSQLFileList = Common.GetSQLItemSQLFileList(this.group);
            //                foreach (Source source in sourceList)
            //                {
            //                    string[] strArray = Directory.GetFiles(source.source, "*.sql", source.recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
            //                    foreach (string str in strArray)
            //                    {
            //                        if (!sQLItemSQLFileList.ContainsKey(str))
            //                        {
            //                            string str4;
            //                            string[] strArray2;
            //                            SQLItem item = new SQLItem(str, "sqlfile", this.group, connection);
            //                            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(str);
            //                            string pattern = "[0-9]+_[0-9]+_[a-zA-Z0-9]+_.*";
            //                            if (Regex.IsMatch(fileNameWithoutExtension, pattern))
            //                            {
            //                                str4 = "([0-9]+)_([0-9]+)_([a-zA-Z0-9]+)_(.*)";
            //                                strArray2 = Regex.Replace(fileNameWithoutExtension, str4, "$1\t$2\t$3\t$4").Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
            //                                item.connectionstringid = connectionStringNameIdList[strArray2[2]];
            //                                item.revision = strArray2[0].IntValueOrZero();
            //                                item.index = strArray2[1].IntValueOrZero();
            //                            }
            //                            else
            //                            {
            //                                pattern = "[0-9]+_[0-9]+_[a-zA-Z0-9]";
            //                                if (Regex.IsMatch(fileNameWithoutExtension, pattern))
            //                                {
            //                                    str4 = "([0-9]+)_([0-9]+)_([a-zA-Z0-9]+)";
            //                                    strArray2 = Regex.Replace(fileNameWithoutExtension, str4, "$1\t$2\t$3").Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
            //                                    item.connectionstringid = connectionStringNameIdList[strArray2[2]];
            //                                    item.revision = strArray2[0].IntValueOrZero();
            //                                    item.index = strArray2[1].IntValueOrZero();
            //                                }
            //                            }
            //                            item.SaveOrUpdate(command, errors);
            //                        }
            //                    }
            //                }
            //                transaction.Commit();
            //            }
            //        }
            //    }
            //}
            //catch (Exception exception)
            //{
            //    errors.AppendLine(string.Format("Error: {0}", exception.Message));
            //}
            //if (errors.Length > 0)
            //{
            //    MessageBox.Show(errors.ToString());
            //}
            //this.UpdateViewer();
        }

        private void Save(bool apply)
        {
            //this.UpdateObject();
            //StringBuilder builder = this.group.SaveOrUpdate();
            //if (builder.Length > 0)
            //{
            //    MessageBox.Show(builder.ToString());
            //}
            //else
            //{
            //    this._uiHandler.groupPanel.UpdateViewer();
            //    if (!apply)
            //    {
            //        base.Close();
            //    }
            //}
        }

        private void tabMain_TabIndexChanged(object sender, EventArgs e)
        {
            //if (this.tabMain.SelectedTab == this.tabSQLItems)
            //{
            //    this.mySQLItemList.UpdateViewer();
            //}
            //else if (this.tabMain.SelectedTab == this.tabSources)
            //{
            //    this.mySourceList.UpdateViewer();
            //}
            //else if (this.tabMain.SelectedTab == this.tabLogs)
            //{
            //    this.myLogList.UpdateViewer();
            //}
            //else if (this.tabMain.SelectedTab == this.tabSQLItems)
            //{
            //    this.myConnectionStringList.UpdateViewer();
            //}
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            //this.Text = "Group: " + this.txtGroupName.Text + " " + this.txtCurrentRevision.Text;
        }

        private void txtRevision_TextChanged(object sender, EventArgs e)
        {
            //this.Text = "Group: " + this.txtGroupName.Text + " " + this.txtCurrentRevision.Text;
        }


 

       
    }
}
